import { defineStore } from 'pinia'

interface HistoryItem {
  id: string
  expression: string
  result: string
  timestamp: string
}

interface CalculatorState {
  history: HistoryItem[]
}

export const useCalculatorStore = defineStore('calculator', {
  state: (): CalculatorState => ({
    history: [],
  }),

  actions: {
    // 添加历史记录
    addHistory(item: HistoryItem) {
      this.history.unshift(item)
      // 限制历史记录数量
      if (this.history.length > 50) {
        this.history.pop()
      }
    },

    // 清空历史记录
    clearHistory() {
      this.history = []
    },

    // 删除指定历史记录
    deleteHistoryItem(id: string) {
      const index = this.history.findIndex(item => item.id === id)
      if (index > -1) {
        this.history.splice(index, 1)
      }
    },

    // 使用历史记录项
    useHistoryItem(item: HistoryItem) {
      return {
        expression: item.expression,
        result: item.result,
      }
    },
  },

  persist: {
    key: 'ECHO-CALCULATOR',
    storage: {
      getItem: (key: string) => {
        return uni.getStorageSync(key)
      },
      setItem: (key: string, value: any) => {
        uni.setStorageSync(key, value)
      },
    },
  },
})
